/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package system;

/**
 *
 * @author Dhruv
 */

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import java.sql.Connection;
import java.sql.Statement;
import database.Database;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.sql.SQLException;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeSelectionModel;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Calendar;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JRadioButton;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;
import javax.swing.table.TableModel;

public class EmailEngine implements TreeSelectionListener, MouseListener, ActionListener {
    //variables for tree
    private JTree tree;
    private JSplitPane treeAndTools;
    private JScrollPane treeView;
    private DefaultMutableTreeNode top;
    //splitpane used when composing a new e-mail, or moving or forwarding
    private JSplitPane splitPane;
    //splitpane used to separate e-mail metadata from body in main page
    private JSplitPane contentView;
    //variables for table
    private JTable table, searchTable;
    private JScrollPane tableView, searchTableView;
    private MyTableModel currentTableModel, searchTableModel;
    //main panel which is used in the main JFrame
    private JPanel panel;
    //the various toolbars used
    private JToolBar buttonBar, buttonBarNew, buttonBarDoubleClick;
    //each string is associated with an action listener
    static final private String NEW = "new";
    static final private String MOVE = "move";
    static final private String EFFECTMOVE = "effectmove";
    static final private String EFFECTSEARCH = "effectsearch";
    static final private String DELETE = "delete";
    static final private String REPLY = "reply";
    static final private String FORWARD = "forward";
    static final private String EMPTY = "empty";
    static final private String SEARCH = "search";
    static final private String OPEN = "open";
    static final private String SAVE = "save";
    static final private String SEND = "send";
    static final private String EXIT = "exit";
    static final private String TREEINBOX = "treeinbox";
    static final private String TREEOUTBOX = "treeoutbox";
    static final private String TREEJUNK = "treejunk";
    static final private String TREEDRAFTS = "treedrafts";
    static final private String TREEDELETED = "treedeleted";
    static final private String inboxString = "inbox";
    static final private String outboxString = "outbox";
    static final private String junkString = "junk";
    static final private String draftsString = "drafts";
    static final private String deletedString = "deleted";
    static final private String uniString = "university";
    static final private String workString = "work";
    //add these buttons to the toolbars
    private JButton button = new JButton(new ImageIcon("new.jpg"));
    private JButton button2 = new JButton(new ImageIcon("move.jpg"));
    private JButton button4 = new JButton(new ImageIcon("delete.jpg"));
    private JButton button5 = new JButton(new ImageIcon("reply.jpg"));
    private JButton button6 = new JButton(new ImageIcon("forward.jpg"));
    private JButton button7 = new JButton(new ImageIcon("empty.jpg"));
    private JButton button8 = new JButton(new ImageIcon("search.jpg"));
    private JButton button9 = new JButton(new ImageIcon("send.jpg"));
    private JButton button10 = new JButton(new ImageIcon("save.jpg"));
    private JButton button11 = new JButton(new ImageIcon("reply.jpg"));
    private JButton button12 = new JButton(new ImageIcon("forward.jpg"));
    private JButton button13 = new JButton(new ImageIcon("move.jpg"));
    private JButton button14 = new JButton(new ImageIcon("delete.jpg"));
    //image icons used for decorative purposes
    private ImageIcon inboxIcon = new ImageIcon("inbox.png");
    private ImageIcon outboxIcon = new ImageIcon("outbox.png");
    private ImageIcon draftIcon = new ImageIcon("draft.png");
    private ImageIcon junkIcon = new ImageIcon("junk.png");
    private ImageIcon deletedIcon = new ImageIcon("deleted.png");
    private ImageIcon uniIcon = new ImageIcon("uni.png");
    private ImageIcon workIcon = new ImageIcon("work.png");
    private ImageIcon exitIcon = new ImageIcon("exit.png");
    private ImageIcon newMIcon = new ImageIcon("newM.png");
    private ImageIcon openMIcon = new ImageIcon("openM.png");
    private ImageIcon replyMIcon = new ImageIcon("replyM.png");
    private ImageIcon forwardMIcon = new ImageIcon("forwardM.png");
    private ImageIcon deleteMIcon = new ImageIcon("deleteM.png");
    private ImageIcon moveMIcon = new ImageIcon("moveM.png");
    private ImageIcon searchMIcon = new ImageIcon("searchM.png");
    private ImageIcon decorativeIcon = new ImageIcon("email.png");
    private ImageIcon decorativeIcon2 = new ImageIcon("books.png");
    private ImageIcon decorativeIcon3 = new ImageIcon("welcome.png");
    //current selcted row; -1 is none selected
    private int row;
    //menu items for popup menu (right click on e-mail)
    private JMenuItem popupMenuItem, popupMenuItem2, popupMenuItem3,
            popupMenuItem4, popupMenuItem5;
    //menu items for NORTHMOST menu
    private JMenuItem menuItem, menuItem2, menuItem3, menuItem4, menuItem5,
            menuItem6, menuItem7, menuItem8, inboxMenu, outboxMenu, junkMenu,
            draftsMenu, deleteMenu;
    //holds all the popup menu items
    private JPopupMenu popup;
    //holds all the NORTHMOST menu items
    private JMenuBar menuBar = new JMenuBar();
    //holds current selected node
    private String currentNode;
    //menu items in the main menubar
    private JMenu menu, menu2, menu3, submenu;
    //private final JButton toolButton;
    private final JPanel toolPanel;
    //quick access buttons which appear on the bottom left of the main JFrame
    private final JButton toolButtonInbox, toolButtonOutbox, toolButtonDeleted
            , toolButtonExit;
    //top and bottom text which are added to a splitpane
    private JTextArea topText, bottomText;
    //input text to search for e-mail by sender
    private JTextArea sendTA;
    //various fields used to embellish an e-mail
    private JTextField toField = new JTextField();
    private JTextField ccField = new JTextField();
    private JTextField titleField = new JTextField();
    private JTextArea contentsArea = new JTextArea();
    //used for displaying purposes when move e-mail button is clicked
    private JPanel movePanel = new JPanel();
    //radio buttons which are layout in the above JPanel (movePanel)
    private JRadioButton inboxButton, outboxButton, junkButton,
            draftsButton, deletedButton, uniButton, workButton;
    //button to effect a move on an e-mail
    private JButton move, search;
    //used to group radio buttons
    private ButtonGroup group;
    //border used to style buttons
    private Border raisedbevel;
    //used to display the results of various events
    private JFrame f = null;
    //decorative labels
    private JLabel decorativeLabel, decorativeLabel2, decorativeLabel3;
    //decorative panels
    private JPanel decorativePanel, decorativePanel2;

    //constructor
    public EmailEngine() {

        //chosen row of table
        row = -1;

        //border for bottom-left buttons which appear on the main JFrame
        raisedbevel = BorderFactory.createRaisedBevelBorder();

        //MOVE BUTTON
        //button effects a move of an e-mail
        move = new JButton("Move", moveMIcon);
        move.setBackground(new Color(160, 205, 255));
        move.setBorder(raisedbevel);
        move.setActionCommand(EFFECTMOVE);
        move.addActionListener(this);

        //SEARCH BUTTON
        //button effects a search of e-mail by sender
        search = new JButton("Search", searchMIcon);
        search.setBackground(new Color(160, 205, 255));
        search.setBorder(raisedbevel);
        search.setActionCommand(EFFECTSEARCH);
        search.addActionListener(this);

        //RADIO BUTTONS
        //radio buttons used when you move an e-mail
        //strings identify the which button fired the event
        inboxButton = new JRadioButton(inboxString);
        inboxButton.setActionCommand(inboxString);
        //default selection is "move to inbox"
        inboxButton.setSelected(true);
        outboxButton = new JRadioButton(outboxString);
        outboxButton.setActionCommand(outboxString);
        junkButton = new JRadioButton(junkString);
        junkButton.setActionCommand(junkString);
        draftsButton = new JRadioButton(draftsString);
        draftsButton.setActionCommand(draftsString);
        deletedButton = new JRadioButton(deletedString);
        deletedButton.setActionCommand(deletedString);
        uniButton = new JRadioButton(uniString);
        uniButton.setActionCommand(uniString);
        workButton = new JRadioButton(workString);
        workButton.setActionCommand(workString);
        //background colours for the radio buttons
        inboxButton.setBackground(new Color(202, 225, 255));
        outboxButton.setBackground(new Color(202, 225, 255));
        junkButton.setBackground(new Color(202, 225, 255));
        draftsButton.setBackground(new Color(202, 225, 255));
        deletedButton.setBackground(new Color(202, 225, 255));
        uniButton.setBackground(new Color(202, 225, 255));
        workButton.setBackground(new Color(202, 225, 255));
        //group the radio buttons.
        group = new ButtonGroup();
        group.add(inboxButton);
        group.add(outboxButton);
        group.add(junkButton);
        group.add(draftsButton);
        group.add(deletedButton);
        group.add(uniButton);
        group.add(workButton);
        //register listeners for the radio buttons
        inboxButton.addActionListener(this);
        outboxButton.addActionListener(this);
        junkButton.addActionListener(this);
        draftsButton.addActionListener(this);
        deletedButton.addActionListener(this);
        uniButton.addActionListener(this);
        workButton.addActionListener(this);
        //put the radio buttons in a column in a panel
        JPanel radioPanel = new JPanel(new GridLayout(0, 1));
        radioPanel.add(inboxButton);
        radioPanel.add(outboxButton);
        radioPanel.add(junkButton);
        radioPanel.add(draftsButton);
        radioPanel.add(deletedButton);
        radioPanel.add(uniButton);
        radioPanel.add(workButton);
        //add the buttons to a JPanel; panel will be displayed
        //when user clicks on the move e-mail button
        movePanel.add(radioPanel);
        movePanel.setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
        movePanel.setBackground(new Color(202, 225, 255));

        //TEXTFIELDS
        //used when you send new e-mail or reply or forward an e-mail
        //set the column width
        toField.setColumns(60);
        ccField.setColumns(60);
        titleField.setColumns(60);
        //register listeners for the textfields
        toField.addActionListener(this);
        ccField.addActionListener(this);
        titleField.addActionListener(this);

        //MENUBAR
        //build the first menu
        menu = new JMenu("File");
        menuBar.add(menu);
        //a group of JMenuItems
        menuItem = new JMenuItem("New", newMIcon);
        menuItem.setActionCommand(NEW);
        menuItem.addActionListener(this);
        menu.add(menuItem);
        //a group of JMenuItems
        menuItem2 = new JMenuItem("Open", openMIcon);
        menuItem2.setActionCommand(OPEN);
        menuItem2.addActionListener(this);
        menu.add(menuItem2);

        //a submenu for folders
        menu.addSeparator();
        submenu = new JMenu("Folders");

        inboxMenu = new JMenuItem("Inbox", inboxIcon);
        inboxMenu.setActionCommand(TREEINBOX);
        inboxMenu.addActionListener(this);
        submenu.add(inboxMenu);
        outboxMenu = new JMenuItem("Outbox", outboxIcon);
        outboxMenu.setActionCommand(TREEOUTBOX);
        outboxMenu.addActionListener(this);
        submenu.add(outboxMenu);
        junkMenu = new JMenuItem("Junk", junkIcon);
        junkMenu.setActionCommand(TREEJUNK);
        junkMenu.addActionListener(this);
        submenu.add(junkMenu);
        draftsMenu = new JMenuItem("Drafts", draftIcon);
        draftsMenu.setActionCommand(TREEDRAFTS);
        draftsMenu.addActionListener(this);
        submenu.add(draftsMenu);
        deleteMenu = new JMenuItem("Deleted", deletedIcon);
        deleteMenu.setActionCommand(TREEDELETED);
        deleteMenu.addActionListener(this);
        submenu.add(deleteMenu);
        
        menu.add(submenu);
        //end submenu

        //a group of JMenuItems
        menuItem4 = new JMenuItem("Exit", exitIcon);
        menuItem4.setActionCommand(EXIT);
        menuItem4.addActionListener(this);
        menu.add(menuItem4);
        //build the second menu
        menu2 = new JMenu("Actions");
        menuBar.add(menu2);
        //a group of JMenuItems
        menuItem5 = new JMenuItem("Reply", replyMIcon);
        menuItem5.setActionCommand(REPLY);
        menuItem5.addActionListener(this);
        menu2.add(menuItem5);
        //a group of JMenuItems
        menuItem6 = new JMenuItem("Forward", forwardMIcon);
        menuItem6.setActionCommand(FORWARD);
        menuItem6.addActionListener(this);
        menu2.add(menuItem6);
        //a group of JMenuItems
        menuItem3 = new JMenuItem("Search", searchMIcon);
        menuItem3.setActionCommand(SEARCH);
        menuItem3.addActionListener(this);
        menu2.add(menuItem3);
        //build the second menu
        menu3 = new JMenu("Edit");
        menuBar.add(menu3);
        //a group of JMenuItems
        menuItem7 = new JMenuItem("Delete", deleteMIcon);
        menuItem7.setActionCommand(DELETE);
        menuItem7.addActionListener(this);
        menu3.add(menuItem7);
        //a group of JMenuItems
        menuItem8 = new JMenuItem("Move", moveMIcon);
        menuItem8.setActionCommand(MOVE);
        menuItem8.addActionListener(this);
        menu3.add(menuItem8);

        //TREE
        //root node
        top = new DefaultMutableTreeNode("DHRUV");
        //create node structure using the root node
        createNodes(top);
        //create a tree that allows one selection at a time
        tree = new JTree(top);
        tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
        //listen for when the selection changes
        tree.addTreeSelectionListener(this);
        //cell renderer displays custom icons for the tree nodes
        tree.setCellRenderer(new MyRenderer(inboxIcon, outboxIcon, junkIcon, draftIcon,
                deletedIcon, uniIcon, workIcon));
        //in case tree expands, we need a scroll pane
        treeView = new JScrollPane(tree);
        treeView.setMinimumSize(new Dimension(200, 900));

        //BUTTONS
        //appear on bottom left corner of the main JFrame
        toolButtonInbox = new JButton("Inbox", inboxIcon);
        toolButtonInbox.setBorder(raisedbevel);
        toolButtonOutbox = new JButton("Outbox", outboxIcon);
        toolButtonOutbox.setBorder(raisedbevel);
        toolButtonDeleted = new JButton("Deleted", deletedIcon);
        toolButtonDeleted.setBorder(raisedbevel);
        toolButtonExit = new JButton("Exit Now", exitIcon);
        toolButtonExit.setBorder(raisedbevel);
        //associate each button with a string and
        //also register listeners for the buttons
        toolButtonInbox.setActionCommand(TREEINBOX);
        toolButtonInbox.addActionListener(this);
        toolButtonOutbox.setActionCommand(TREEOUTBOX);
        toolButtonOutbox.addActionListener(this);
        toolButtonDeleted.setActionCommand(TREEDELETED);
        toolButtonDeleted.addActionListener(this);
        toolButtonExit.setActionCommand(EXIT);
        toolButtonExit.addActionListener(this);
        //set background colour for each button
        toolButtonInbox.setBackground(new Color(160, 205, 255));
        toolButtonOutbox.setBackground(new Color(160, 205, 255));
        toolButtonDeleted.setBackground(new Color(160, 205, 255));
        toolButtonExit.setBackground(new Color(160, 205, 255));
        //adjust button size
        toolButtonInbox.setPreferredSize(new Dimension(200, 39));
        toolButtonOutbox.setPreferredSize(new Dimension(200, 39));
        toolButtonDeleted.setPreferredSize(new Dimension(200, 39));
        toolButtonExit.setPreferredSize(new Dimension(200, 39));

        //SPLITPANE
        //which has tree as top component and buttons as bottom
        //appears on the left side on the main JFrame
        treeAndTools = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
        //below panel will be the bottom component of the split pane
        toolPanel = new JPanel();
        toolPanel.setBackground(new Color(120, 145, 255));
        //add the buttons to the bottom component
        toolPanel.add(toolButtonInbox, BorderLayout.NORTH);
        toolPanel.add(toolButtonOutbox, BorderLayout.CENTER);
        toolPanel.add(toolButtonDeleted, BorderLayout.LINE_END);
        toolPanel.add(toolButtonExit, BorderLayout.SOUTH);
        toolPanel.setMinimumSize(new Dimension(200,100));
        //the tree is the top component
        treeAndTools.setTopComponent(treeView);
        treeAndTools.setBottomComponent(toolPanel);
        //adjust the split pane; also prevent divider from moving
        treeAndTools.setDividerLocation(415);
        treeAndTools.setPreferredSize(new Dimension(200, 100));

        //TABLE
        //custom model is used to hold the data of the table
        currentTableModel = new MyTableModel();
        table = new JTable(currentTableModel);
        //sets the preferred size of the viewport for this table
        table.setPreferredScrollableViewportSize(new Dimension(500, 70));
        table.setFillsViewportHeight(true);
        //can only select one row at a time
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        //table colums cannot be reordered
        table.getTableHeader().setReorderingAllowed(false);
        //do not show the table grids
        table.setShowGrid(false);
        //register a mouse listener with this table
        table.addMouseListener(this);
        table.getTableHeader().setBackground(new Color(202, 225, 255));
        table.setBackground(new Color(240, 248, 255));
        //in case there are too many e-mails, we need a scroll pane
        tableView = new JScrollPane(table);
        tableView.setPreferredSize(new Dimension(600, 700));

        //SEARCH TABLE
        //search all e-mails by sender
        //custom model is used to hold the data of the search table
        searchTableModel = new MyTableModel();
        searchTable = new JTable(searchTableModel);
        //sets the preferred size of the viewport for this table
        searchTable.setPreferredScrollableViewportSize(new Dimension(50, 70));
        searchTable.setFillsViewportHeight(true);
        //can only select one row at a time
        searchTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        //table colums cannot be reordered
        searchTable.getTableHeader().setReorderingAllowed(false);
        //do not show the table grids
        searchTable.setShowGrid(false);
        //register a mouse listener with this table
        searchTable.addMouseListener(this);
        searchTable.getTableHeader().setBackground(new Color(202, 225, 255));
        searchTable.setBackground(new Color(240, 248, 255));
        //in case there are too many e-mails, we need a scroll pane
        searchTableView = new JScrollPane(searchTable);
        searchTableView.setPreferredSize(new Dimension(60, 70));

        //TEXT AREAS
        //appear on the right side of the main JFrame
        topText = new JTextArea();
        bottomText = new JTextArea();
        //splitpane used to separate e-mail metadata from body
        contentView = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
        contentView.setPreferredSize(new Dimension(430, 200));
        //cannot edit the information
        bottomText.setEditable(false);
        topText.setEditable(false);
        topText.setBackground(new Color(202, 225, 255));
        topText.setMinimumSize(new Dimension(90,450));
        bottomText.setMinimumSize(new Dimension(90,450));
        contentView.setBorder(null);
        //add decorative components to the splitpane;
        //these will be replaced by the text areas
        //once the user makes an e-mail selection
        decorativeLabel = new JLabel(decorativeIcon);
        decorativeLabel2 = new JLabel(decorativeIcon2);
        decorativeLabel3 = new JLabel(decorativeIcon3);
        decorativeLabel.setMinimumSize(new Dimension(90,450));
        decorativeLabel2.setMinimumSize(new Dimension(90,450));
        decorativePanel = new JPanel();
        decorativePanel2 = new JPanel();
        decorativePanel.add(decorativeLabel, BorderLayout.CENTER);
        decorativePanel2.add(decorativeLabel2, BorderLayout.CENTER);
        decorativePanel2.add(decorativeLabel3, BorderLayout.SOUTH);
        decorativePanel.setBackground(new Color(202, 225, 255));
        decorativePanel2.setBackground(Color.WHITE);
        contentView.setTopComponent(decorativePanel);
        contentView.setBottomComponent(decorativePanel2);
        contentView.setDividerLocation(90);

        //VARIOUS TOOLBARS
        //appear on the NORTH of the main page
        //or on the reply/forward page
        //below toolbar appears on the main JFrame,
        //positioned NORTH on the main JPanel
        buttonBar = new JToolBar();
        //below toolbar appears when you compose a new
        //mail, reply to an e-mail or forward an e-mail
        buttonBarNew = new JToolBar();
        //below toolbar appears when you double click an e-mail
        buttonBarDoubleClick = new JToolBar();

        //make some modifications on the toolbars
        buttonBar.setBackground(new Color(160, 205, 255));
        buttonBar.setFloatable(false);
        buttonBar.setBorder(null);
        buttonBarNew.setBackground(new Color(160, 205, 255));
        buttonBarNew.setFloatable(false);
        buttonBarNew.setBorder(null);
        buttonBarDoubleClick.setBackground(new Color(160, 205, 255));
        buttonBarDoubleClick.setFloatable(false);
        buttonBarDoubleClick.setBorder(null);


        //START ADDING BUTTONS
        //the various buttons are added to the respective toolbars
        //each button has a string which is associated with it
        //each button is also registered with an action listener
        button.setActionCommand(NEW);
        button.setToolTipText("new e-mail");
        button.addActionListener(this);
        button.setBackground(new Color(160, 205, 255));
        //add button to toolbar
        buttonBar.add(button);

        button2.setActionCommand(MOVE);
        button2.setToolTipText("move e-mail");
        button2.addActionListener(this);
        button2.setBackground(new Color(160, 205, 255));
        //add button to toolbar
        buttonBar.add(button2);

        button4.setActionCommand(DELETE);
        button4.setToolTipText("delete e-mail");
        button4.setBackground(new Color(160, 205, 255));
        button4.addActionListener(this);
        //add button to toolbar
        buttonBar.add(button4);

        button5.setActionCommand(REPLY);
        button5.setToolTipText("reply e-mail");
        button5.setBackground(new Color(160, 205, 255));
        button5.addActionListener(this);
        //add button to toolbar
        buttonBar.add(button5);

        button6.setActionCommand(FORWARD);
        button6.setToolTipText("forward e-mail");
        button6.setBackground(new Color(160, 205, 255));
        button6.addActionListener(this);
        //add button to toolbar
        buttonBar.add(button6);

        button7.setActionCommand(EMPTY);
        button7.setToolTipText("empty deleted");
        button7.addActionListener(this);
        button7.setBackground(new Color(160, 205, 255));
        //add button to toolbar
        buttonBar.add(button7);

        button8.setActionCommand(SEARCH);
        button8.setToolTipText("search e-mail");
        button8.addActionListener(this);
        button8.setBackground(new Color(160, 205, 255));
        //add button to toolbar
        buttonBar.add(button8);

        button9.setActionCommand(SEND);
        button9.setToolTipText("send e-mail");
        button9.addActionListener(this);
        button9.setBackground(new Color(160, 205, 255));
        //add button to toolbar
        buttonBarNew.add(button9);

        button10.setActionCommand(SAVE);
        button10.setToolTipText("save to drafts");
        button10.addActionListener(this);
        button10.setBackground(new Color(160, 205, 255));
        //add button to toolbar
        buttonBarNew.add(button10);

        button11.setActionCommand(REPLY);
        button11.setToolTipText("reply e-mail");
        button11.addActionListener(this);
        button11.setBackground(new Color(160, 205, 255));
        //add button to toolbar
        buttonBarDoubleClick.add(button11);

        button12.setActionCommand(FORWARD);
        button12.setToolTipText("forward e-mail");
        button12.addActionListener(this);
        button12.setBackground(new Color(160, 205, 255));
        //add button to toolbar
        buttonBarDoubleClick.add(button12);

        button13.setActionCommand(MOVE);
        button13.setToolTipText("move e-mail");
        button13.addActionListener(this);
        button13.setBackground(new Color(160, 205, 255));
        //add button to toolbar
        buttonBarDoubleClick.add(button13);

        button14.setActionCommand(DELETE);
        button14.setToolTipText("delete e-mail");
        button14.addActionListener(this);
        button14.setBackground(new Color(160, 205, 255));
        //add button to toolbar
        buttonBarDoubleClick.add(button14);
        //END ADDING BUTTONS

        //POPUPMENU
        //appears on right click of an e-mail
        //create the popup menu
        popup = new JPopupMenu();

        //ADD MENU ITEMS TO POPUPMENU
        //each menu item has a string which is associated with it
        //each menu item is also registered with an action listener
        popupMenuItem = new JMenuItem("Open", openMIcon);
        popupMenuItem.setActionCommand(OPEN);
        popupMenuItem.addActionListener(this);
        popup.add(popupMenuItem);

        popupMenuItem2 = new JMenuItem("Reply", replyMIcon);
        popupMenuItem2.setActionCommand(REPLY);
        popupMenuItem2.addActionListener(this);
        popup.add(popupMenuItem2);

        popupMenuItem3 = new JMenuItem("Forward", forwardMIcon);
        popupMenuItem3.setActionCommand(FORWARD);
        popupMenuItem3.addActionListener(this);
        popup.add(popupMenuItem3);

        popupMenuItem4 = new JMenuItem("Delete", deleteMIcon);
        popupMenuItem4.setActionCommand(DELETE);
        popupMenuItem4.addActionListener(this);
        popup.add(popupMenuItem4);

        popupMenuItem5 = new JMenuItem("Move", moveMIcon);
        popupMenuItem5.setActionCommand(MOVE);
        popupMenuItem5.addActionListener(this);
        popup.add(popupMenuItem5);

        //register listener with the table so the popup menu can come up
        MouseListener popupListener = new PopupListener(popup);
        table.addMouseListener(popupListener);

        //MAIN PANEL
        //main panel arranges eveything except the NORTHMOST
        //menubar, which is arranged by the main JFRAME
        panel= new JPanel(new BorderLayout());
        panel.add(treeAndTools,BorderLayout.WEST);
        panel.add(tableView,BorderLayout.CENTER);
        panel.add(contentView,BorderLayout.EAST);
        panel.add(buttonBar, BorderLayout.NORTH);
    }

    //action event on listeners triggers this method
    public void actionPerformed(ActionEvent e) {
        //gets the action command
    	String cmd = e.getActionCommand();

        //BUTTONS
        //which appear on bottom left corner of the main JFrame
        //inbox button and menuitem selects tree's inbox node
        if(TREEINBOX.equals(cmd)){
            tree.expandRow(1);
            tree.setSelectionRow(2);
        }
        //outbox button and menuitem selects tree's outbox node
        if(TREEOUTBOX.equals(cmd)){
            tree.expandRow(1);
            tree.setSelectionRow(3);
        }
        //junk menuitem selects tree's junk node
        if(TREEJUNK.equals(cmd)){
            tree.expandRow(1);
            tree.setSelectionRow(4);
        }
        //drafts menuitem selects tree's drafts node
        if(TREEDRAFTS.equals(cmd)){
            tree.expandRow(1);
            tree.setSelectionRow(5);
        }
        //delete button and menuitem selects tree's delete node
        if(TREEDELETED.equals(cmd)){
            tree.expandRow(1);
            tree.setSelectionRow(6);
        }
        //exit button selects tree's exit node
        if(EXIT.equals(cmd)){
            System.exit(0);
        }

        //OPEN E-MAIL
        if(OPEN.equals(cmd)) {
            //make sure you have selected a row
            if(row > -1) {
                openEmail();
            } else {
                JFrame f = new JFrame();
                JOptionPane.showMessageDialog(f,
                                            "Please select an e-mail to open",
                                            "Error",
                                            JOptionPane.ERROR_MESSAGE);
            }
        }

    	//COMPOSE NEW E-MAIL
    	if(NEW.equals(cmd)) {

            //if the JFrame doesn't exit
            if(f == null)
                f = new JFrame();
            else {
                //remove the JFrame
                f.setVisible(false);
                f.dispose();
                //create a new one
                f = new JFrame();
            }

            //labels for the fields
            JLabel to = new JLabel("To:   ");
            JLabel cc = new JLabel("Cc:   ");
            JLabel title = new JLabel("Title: ");
            //scrollpane needed in case the of a large e-mail body
            JScrollPane contentScroll= new JScrollPane(contentsArea);
            //panels used for layout purposes
            JPanel decor = new JPanel();
            JPanel decor2 = new JPanel();
            JPanel decor3 = new JPanel();

            toField.setText("");
            ccField.setText("");
            titleField.setText("");
            contentsArea.setText("");
            //layout cc label and cc textfield
            decor.add(cc, BorderLayout.WEST);
            decor.add(ccField, BorderLayout.EAST);
            decor.setBackground(new Color(202, 225, 255));
            //layout title label and title textfield
            decor3.add(title, BorderLayout.WEST);
            decor3.add(titleField, BorderLayout.EAST);
            decor3.setBackground(new Color(202, 225, 255));
            //layout to label and to textfield
            decor2.add(to, BorderLayout.WEST);
            decor2.add(toField, BorderLayout.EAST);
            //layout all the labels and textfields
            decor2.add(decor, BorderLayout.NORTH);
            decor2.add(decor3, BorderLayout.SOUTH);
            decor2.setMinimumSize(new Dimension(100,100));
            decor2.setBackground(new Color(202, 225, 255));
            contentScroll.setMinimumSize(new Dimension(100,450));

            //splitpane used to seprate e-mail body from the rest
            splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
            splitPane.setTopComponent(decor2);
            splitPane.setBottomComponent(contentScroll);
            splitPane.setDividerLocation(100);
            splitPane.setBorder(null);

            //layout everything in the frame
            f.add(buttonBarNew, BorderLayout.NORTH);
            f.add(splitPane, BorderLayout.CENTER);
            f.setTitle("New E-mail");
            f.setVisible(true);
            f.setSize(800, 600);
            //this centers the frame on the screen
            f.setLocationRelativeTo(null);
        }

        //MOVE E-MAIL
        if(MOVE.equals(cmd)) {
            //make sure you have selected a row
            if(row > -1) {

                //if the JFrame doesn't exit
                if(f == null)
                    f = new JFrame();
                else {
                    //remove the JFrame
                    f.setVisible(false);
                    f.dispose();
                    //create a new one
                    f = new JFrame();
                }

                //put the move button on a panel
                JPanel temp = new JPanel();
                temp.add(move);
                temp.setBackground(new Color(202, 225, 255));

                //layout everything in the frame
                f.add(movePanel, BorderLayout.CENTER);
                f.add(temp, BorderLayout.SOUTH);
                f.setTitle("Move E-mail");
                f.setVisible(true);
                f.setSize(300, 300);
                //this centers the frame on the screen
                f.setLocationRelativeTo(null);
            } else {

                JFrame f = new JFrame();
                JOptionPane.showMessageDialog(f,
                                            "Please select an e-mail to move",
                                            "Error",
                                            JOptionPane.ERROR_MESSAGE);

            }
        }

        //DELETE E-MAIL
        ///sends to deleted folder
        if(DELETE.equals(cmd)) {
            //make sure you have selected a row and the
            //current folder is not already the deleted folder
            if(row > -1 && !this.currentNode.equals("deleted")) {
                //if the JFrame doesn't exit
                if(f == null)
                    f = new JFrame();
                else {
                    //remove the JFrame
                    f.setVisible(false);
                    f.dispose();
                    //create a new one
                    f = new JFrame();
                }

                TableModel model = (TableModel)table.getModel();
                ArrayList<EmailMetadata> tableMeta = currentTableModel.getTableMetaData();
                //identify the e-mail selected, get the cell values
                String timeReceived = (String)model.getValueAt(row,0);
                String sender = (String)model.getValueAt(row,1);
                String epoch = convertEpoch(timeReceived);
                //make the update to the deleted folder
                updateEmail("deleted", epoch, sender);
                tableMeta.remove(row);
                //reset row selection
                row = -1;
                //update the table display
                table.removeAll();
                currentTableModel.setTableData(tableMeta);
                table.setModel(currentTableModel);
                panel.repaint();

            } else {

                JFrame f = new JFrame();
                //if current folder is not deleted folder
                //then you have not made a selection
                //else, this mail is already deleted
                if(!this.currentNode.equals("deleted"))
                    JOptionPane.showMessageDialog(f,
                                                "Please select an e-mail "
                                                + "to delete",
                                                "Error",
                                                JOptionPane.ERROR_MESSAGE);
                else
                    JOptionPane.showMessageDialog(f,
                                                "You are already in the "
                                                + "deleted folder",
                                                "Error",
                                                JOptionPane.ERROR_MESSAGE);
            }
            
        }

        //EFFECT MOVE OF THE E-MAIL
        if(EFFECTMOVE.equals(cmd)){
            //if this email is not already in the correct folder, move it
            if(!this.currentNode.equals(group.getSelection().getActionCommand())){
                //if the JFrame doesn't exit
                if(f == null)
                    f = new JFrame();
                else {
                    //remove the JFrame
                    f.setVisible(false);
                    f.dispose();
                    //create a new one
                    f = new JFrame();
                }

                TableModel model = (TableModel)table.getModel();
                ArrayList<EmailMetadata> tableMeta = currentTableModel.getTableMetaData();
                //identify the e-mail selected, get the cell values
                String timeReceived = (String)model.getValueAt(row,0);
                String sender = (String)model.getValueAt(row,1);
                String epoch = convertEpoch(timeReceived);
                updateEmail(group.getSelection().getActionCommand(), epoch, sender);
                tableMeta.remove(row);
                //reset row selection
                row = -1;
                //update the table display
                table.removeAll();
                currentTableModel.setTableData(tableMeta);
                table.setModel(currentTableModel);
                panel.repaint();
            } else {
                //else, this e-mail is already in the correct folder
                JFrame f = new JFrame();
                JOptionPane.showMessageDialog(f,
                                            "This e-mail is already in the "
                                            + this.currentNode +" folder",
                                            "Error",
                                            JOptionPane.ERROR_MESSAGE);
            }
        }

        //REPLY TO E-MAIL
        if(REPLY.equals(cmd)) {
            //make sure you have selected a row
            if(row > -1) {
                TableModel model = (TableModel)table.getModel();
                ArrayList<EmailMetadata> tableMeta = currentTableModel.getTableMetaData();
                //identify the e-mail selected, get the cell values
                String timeReceived = (String)model.getValueAt(row,0);
                String sender = (String)model.getValueAt(row,1);
                String title = (String)model.getValueAt(row,2);
                String cc = (String)model.getValueAt(row,3);

                //if the JFrame doesn't exit
                if(f == null)
                    f = new JFrame();
                else {
                    //remove the JFrame
                    f.setVisible(false);
                    f.dispose();
                    //create a new one
                    f = new JFrame();
                }

                //labels for the fields
                JLabel to = new JLabel("To:   ");
                JLabel CC = new JLabel("Cc:   ");
                JLabel t = new JLabel("Title: ");
                toField.setText(sender);
                ccField.setText("");
                titleField.setText("RE: "+title);
                //scrollpane needed in case the of a large e-mail body
                JScrollPane contentScroll= new JScrollPane(contentsArea);
                //used for layout purposes
                JPanel decor = new JPanel();
                JPanel decor2 = new JPanel();
                JPanel decor3 = new JPanel();

                contentsArea.setText("\n\n\n\n\n\n"+
                        "ORIGINAL MESSAGE\n\n"+
                        "-----------------------------\n"+
                        "Title:          "+title+"\nSender:    "+sender+
                        "\nWhen:       "+timeReceived+"\nTo:             "
                        +tableMeta.get(0).getReceiver()
                        +"\nCc:             "+cc+"\n\n"+
                        getBody(tableMeta.get(0).getSubtree(),timeReceived, sender));

                //make the layout adjustments
                decor.add(CC, BorderLayout.WEST);
                decor.add(ccField, BorderLayout.EAST);
                decor.setBackground(new Color(202, 225, 255));
                decor3.add(t, BorderLayout.WEST);
                decor3.add(titleField, BorderLayout.EAST);
                decor3.setBackground(new Color(202, 225, 255));
                decor2.add(to, BorderLayout.WEST);
                decor2.add(toField, BorderLayout.EAST);
                decor2.add(decor, BorderLayout.NORTH);
                decor2.add(decor3, BorderLayout.SOUTH);
                //prevents splitpane from moving
                decor2.setMinimumSize(new Dimension(100,100));
                decor2.setBackground(new Color(202, 225, 255));
                contentScroll.setMinimumSize(new Dimension(100,450));

                //use splitpane to separate the e-mail body from the rest
                splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
                splitPane.setTopComponent(decor2);
                splitPane.setBottomComponent(contentScroll);
                splitPane.setDividerLocation(100);
                splitPane.setBorder(null);

                //layout everything in the frame
                f.add(buttonBarNew, BorderLayout.NORTH);
                f.add(splitPane, BorderLayout.CENTER);
                f.setTitle("Reply to E-mail");
                f.setVisible(true);
                f.setSize(800, 600);
                //this centers the frame on the screen
                f.setLocationRelativeTo(null);

            } else {

                JFrame f = new JFrame();
                JOptionPane.showMessageDialog(f,
                                            "Please select an e-mail to reply",
                                            "Error",
                                            JOptionPane.ERROR_MESSAGE);
            }
        }

        //FORWARD AN E-MAIL
        if(FORWARD.equals(cmd)) {
            //make sure you have selected a row
            if(row > -1) {
                TableModel model = (TableModel)table.getModel();
                ArrayList<EmailMetadata> tableMeta = currentTableModel.getTableMetaData();
                //identify the e-mail selected, get the cell values
                String timeReceived = (String)model.getValueAt(row,0);
                String sender = (String)model.getValueAt(row,1);
                String title = (String)model.getValueAt(row,2);
                String cc = (String)model.getValueAt(row,3);

                //if the JFrame doesn't exit
                if(f == null)
                    f = new JFrame();
                else {
                    //remove the JFrame
                    f.setVisible(false);
                    f.dispose();
                    //create a new one
                    f = new JFrame();
                }

                //labels for the fields
                JLabel to = new JLabel("To:   ");
                JLabel CC = new JLabel("Cc:   ");
                JLabel t = new JLabel("Title: ");
                toField.setText("");
                ccField.setText("");
                titleField.setText("FW: "+title);
                JTextArea contentsArea = new JTextArea();
                //scrollpane needed in case the of a large e-mail body
                JScrollPane contentScroll= new JScrollPane(contentsArea);
                //used for layout purposes
                JPanel decor = new JPanel();
                JPanel decor2 = new JPanel();
                JPanel decor3 = new JPanel();

                contentsArea.setText("\n\n\n\n\n\n"+
                        "ORIGINAL MESSAGE\n\n"+
                        "-----------------------------\n"+
                        "Title:          "+title+"\nSender:    "+sender+
                        "\nWhen:       "+timeReceived+"\nTo:             "
                        +tableMeta.get(0).getReceiver()
                        +"\nCc:             "+cc+"\n\n"+
                        getBody(tableMeta.get(0).getSubtree(),timeReceived, sender));

                //make the layout adjustments
                decor.add(CC, BorderLayout.WEST);
                decor.add(ccField, BorderLayout.EAST);
                decor.setBackground(new Color(202, 225, 255));
                decor3.add(t, BorderLayout.WEST);
                decor3.add(titleField, BorderLayout.EAST);
                decor3.setBackground(new Color(202, 225, 255));
                decor2.add(to, BorderLayout.WEST);
                decor2.add(toField, BorderLayout.EAST);
                decor2.add(decor, BorderLayout.NORTH);
                decor2.add(decor3, BorderLayout.SOUTH);
                //prevents splitpane from moving
                decor2.setMinimumSize(new Dimension(100,100));
                decor2.setBackground(new Color(202, 225, 255));
                contentScroll.setMinimumSize(new Dimension(100,450));

                //use splitpane to separate the e-mail body from the rest
                splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
                splitPane.setTopComponent(decor2);
                splitPane.setBottomComponent(contentScroll);
                splitPane.setDividerLocation(100);
                splitPane.setBorder(null);

                //layout everything in the frame
                f.add(buttonBarNew, BorderLayout.NORTH);
                f.add(splitPane, BorderLayout.CENTER);
                f.setTitle("Forward E-mail");
                f.setVisible(true);
                f.setSize(800, 600);
                //this centers the frame on the screen
                f.setLocationRelativeTo(null);
            } else {

                JFrame f = new JFrame();
                JOptionPane.showMessageDialog(f,
                                            "Please select an e-mail to forward",
                                            "Error",
                                            JOptionPane.ERROR_MESSAGE);
            }
        }

        //EMPTY DELETED FOLDER
        if(EMPTY.equals(cmd)) {
            emptyDeleted();
            //if the current node we are looking at is the
            //deleted folder, then we have to update the view
            if(currentNode == "deleted"){
                ArrayList<EmailMetadata> tableMeta = currentTableModel.getTableMetaData();
                tableMeta.removeAll(tableMeta);
                table.removeAll();
                currentTableModel.setTableData(tableMeta);
                table.setModel(currentTableModel);
                panel.repaint();

            }
        }

        //SAVE E-MAIL TO DRAFTS OR SEND E-MAIL (MOVED TO OUTBOX)
        if(SAVE.equals(cmd) || SEND.equals(cmd)) {
            //if the JFrame doesn't exit
            if(f == null)
                f = new JFrame();
            else {
                //remove the JFrame
                f.setVisible(false);
                f.dispose();
                //create a new one
                f = new JFrame();
            }
            //get all the e-mail metadata
            String draftsTo = toField.getText();
            String draftsCC = ccField.getText();
            String draftsTitle = titleField.getText();
            String draftsBody = contentsArea.getText();
            //either send mail to drafts or outbox
            if(SAVE.equals(cmd))
                saveOrSendMail(draftsTo, draftsCC, draftsTitle, draftsBody, "drafts");
            else
                saveOrSendMail(draftsTo, draftsCC, draftsTitle, draftsBody, "outbox");
        }

        //SEARCH FOLDERS
        if(SEARCH.equals(cmd)) {
            //if the JFrame doesn't exit
            if(f == null)
                f = new JFrame();
            else {
                //remove the JFrame
                f.setVisible(false);
                f.dispose();
                //create a new one
                f = new JFrame();
            }

            //put the move button on a panel
            JPanel temp = new JPanel();
            JPanel temp2 = new JPanel();
            JLabel sendL = new JLabel("Sender");
            sendTA = new JTextArea();
            sendTA.setColumns(20);
            temp2.add(sendL, BorderLayout.EAST);
            temp2.add(sendTA, BorderLayout.WEST);
            temp.add(search);
            temp.setBackground(new Color(202, 225, 255));
            temp2.setBackground(new Color(202, 225, 255));

            //layout everything in the frame
            f.add(temp2, BorderLayout.NORTH);
            f.add(searchTableView, BorderLayout.CENTER);
            f.add(temp, BorderLayout.SOUTH);
            f.setTitle("Search");
            f.setVisible(true);
            f.setSize(300, 300);
            //this centers the frame on the screen
            f.setLocationRelativeTo(null);
        }

        //EFFECT SEARCH
        if(EFFECTSEARCH.equals(cmd)) {
            //search criteria i.e. senders name
            String sender = sendTA.getText();
            row = -1;
            //update the search table display
            searchTable.removeAll();
            searchTableModel.setTableData(this.getTitlesBySender(sender));
            searchTable.setModel(searchTableModel);
            searchTableView.repaint();
        }
    }

    //tree selction event on the tree triggers this method
    public void valueChanged(TreeSelectionEvent e) {
        //which node was selected
        DefaultMutableTreeNode node = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
        if (node == null) return;
        Object nodeInfo = node.getUserObject();

        //if node is a leaf
        if (node.isLeaf()) {
            MyTableModel mObj = (MyTableModel)nodeInfo;
            //get name of the current node using the table model
            currentNode = mObj.toString();
            //you need to reset the table model each time
            //in case e-mails have been moved around or deleted
            mObj.setTableMetaData(this.getTitles(mObj.toString()));
            row = -1;
            //update the table display
            table.removeAll();
            currentTableModel.setTableData(mObj.getTableMetaData());
            table.setModel(currentTableModel);
            panel.repaint();
        }
    }

    //mouse click event on the table triggers this method
    public void mouseClicked(MouseEvent e) {
        JTable target = (JTable)e.getSource();
        //get the coordinates of the mouse click
        Point p = e.getPoint();
	//get the row index that contains that coordinate
	row= target.rowAtPoint(p);
        //left mouse click
        if (SwingUtilities.isLeftMouseButton(e)) {
            //if the click was made inside the table
            if(target == table && row >= 0) {
                TableModel model = (TableModel)table.getModel();
                ArrayList<EmailMetadata> tableMeta = currentTableModel.getTableMetaData();
                //get the cell values
                String timeReceived = (String)model.getValueAt(row,0);
                String sender = (String)model.getValueAt(row,1);
                String title = (String)model.getValueAt(row,2);
                String cc = (String)model.getValueAt(row,3);
                String epochTimeReceived = convertEpoch(timeReceived);
                String receiver = getReceiver(epochTimeReceived, sender);
                //remove selected row
                target.removeRowSelectionInterval(0, row);

                //the displayed e-mail changes with the mouse click
                topText.setText("Title:         "+title+"\nSender:    "+sender+
                        "\nWhen:      "+timeReceived+"\nTo:            "
                        +receiver+"\nCc:            "+cc+"\n\n");
                bottomText.setText(getBody(tableMeta.get(0).getSubtree(),timeReceived, sender));

                //remove all the components from the split pane
                //and add the top and bottom text; removal and 
                //readdition is done because the initial components
                //on this splitpane were decorative welcome messages
                contentView.removeAll();
                contentView.setTopComponent(topText);
                contentView.setBottomComponent(bottomText);
                //upon double clicking, open the e-mail
                if (e.getClickCount() == 2) {
                    openEmail();
                }
            }
        }
    }

    //method which creates a new frame to display the e-mail to be opened
    private void openEmail() {

        TableModel model = (TableModel)table.getModel();
        ArrayList<EmailMetadata> tableMeta = currentTableModel.getTableMetaData();
        //get the cell values
        String timeReceived = (String)model.getValueAt(row,0);
        String sender = (String)model.getValueAt(row,1);
        String title = (String)model.getValueAt(row,2);
        String cc = (String)model.getValueAt(row,3);
        String epochTimeReceived = convertEpoch(timeReceived);
        String receiver = getReceiver(epochTimeReceived, sender);

        //if the JFrame doesn't exit
        if(f == null)
            f = new JFrame();
        else {
            //remove the JFrame
            f.setVisible(false);
            f.dispose();
            //create a new one
            f = new JFrame();
        }

        //make the text areas, splitpane and scrollpane to display e-mail info
        JTextArea top = new JTextArea();
        JTextArea bottom = new JTextArea();
        JScrollPane contentScroll= new JScrollPane(bottom);
        JSplitPane sp = new JSplitPane(JSplitPane.VERTICAL_SPLIT);

        top.setText("Title:         "+title+"\nSender:    "+sender+
                "\nWhen:      "+timeReceived+"\nTo:            "
                +receiver+"\nCc:            "+cc+"\n\n");

        bottom.setText(getBody(tableMeta.get(0).getSubtree(),timeReceived, sender));

        //configure the textfields, splitpane and scrollpane
        top.setBackground(new Color(202, 225, 255));
        bottom.setEditable(false);
        top.setMinimumSize(new Dimension(90,450));
        bottom.setMinimumSize(new Dimension(90,250));
        contentScroll.setMinimumSize(new Dimension(90,250));
        top.setEditable(false);
        sp.setBorder(null);
        sp.setTopComponent(top);
        sp.setBottomComponent(contentScroll);
        sp.setDividerLocation(90);

        //layout everything in the frame
        f.add(buttonBarDoubleClick, BorderLayout.NORTH);
        f.add(sp, BorderLayout.CENTER);
        f.setTitle("Open E-mail");
        f.setVisible(true);
        f.setSize(800, 600);
        //this centers the frame on the screen
        f.setLocationRelativeTo(null);
    }

    //returns the current time in a string
    public String getTime() {
        Calendar now = Calendar.getInstance();
        return new Long(now.getTimeInMillis()).toString();
    }

    //interacts with Database to either save the e-mail or send it
    private void saveOrSendMail(String to, String cc, String title, String body, String subtree) {
        Connection conn = Database.getConnection();
        String query = "INSERT INTO mailbox (datetime, subtree, sender, receiver"
                + ", cc, title, body) VALUES ('"+getTime()+"','"+subtree+"','dhruv','"
                + to +"','"+ cc +"','"+ title +"','"+ body + "')";
        try {
            //execute query
            conn.setAutoCommit(false);
            Statement stmt = conn.createStatement();
            stmt.executeUpdate(query);
            conn.commit();
            //Releases this Connection object's database and JDBC resources immediately
            Database.closeDatabase(conn);
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }

    //interacts with Database to return receiver of a particular e-mail
    private String getReceiver(String timeReceived, String sender) {
        Connection conn = Database.getConnection();
        String query = "SELECT receiver FROM mailbox WHERE datetime='"
                + timeReceived +"' AND sender='"+ sender +"'";
        String receiver = "";

        try {
            //execute query
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(query);
            while(rs.next())
            {
                //store the values of the respective column
                //which is determined by column name
                receiver = rs.getString("receiver");
            }
            rs.close();
            //Releases this Connection object's database and JDBC resources immediately
            Database.closeDatabase(conn);
        } catch (SQLException ex) {
            ex.printStackTrace();
        }

        return receiver;
    }

    private ArrayList<EmailMetadata> getTitlesBySender(String sender) {
        Connection conn = Database.getConnection();
        String query = "SELECT * FROM mailbox WHERE sender='"+sender+"'"
                + " ORDER BY datetime DESC";
        //temporary variables
        ArrayList<String> temp1 = new ArrayList<String>();
        ArrayList<String> temp2 = new ArrayList<String>();
        ArrayList<String> temp3 = new ArrayList<String>();
        ArrayList<String> temp4 = new ArrayList<String>();
        ArrayList<String> temp5 = new ArrayList<String>();
        ArrayList<String> temp6 = new ArrayList<String>();
        ArrayList<String> temp7 = new ArrayList<String>();
        //variable to be returned
        ArrayList<EmailMetadata> tableD = new ArrayList<EmailMetadata>();

        try {
            //execute query
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(query);
            while(rs.next())
            {
                //store the values of the respective columns
                //which is determined by column name
                temp1.add(rs.getString("datetime"));
                temp2.add(rs.getString("subtree"));
                temp3.add(rs.getString("sender"));
                temp4.add(rs.getString("receiver"));
                temp5.add(rs.getString("cc"));
                temp6.add(rs.getString("title"));
                temp7.add(rs.getString("body"));
            }
            rs.close();
            //Releases this Connection object's database and JDBC resources immediately
            Database.closeDatabase(conn);
        } catch (SQLException ex) {
            ex.printStackTrace();
        }

        //add the metadata objects to tableD
        for(int i=0;i<temp1.size();i++){
            tableD.add(new EmailMetadata(convertTime(temp1.get(i)),temp2.get(i),temp3.get(i),
                    temp4.get(i),temp5.get(i),temp6.get(i),temp7.get(i)));
        }

        return tableD;
    }

    //listens for the popup on right clicking an e-mail
    class PopupListener extends MouseAdapter {
        JPopupMenu popup;

        PopupListener(JPopupMenu popupMenu) {
            popup = popupMenu;
        }

        public void mousePressed(MouseEvent e) {
            JTable target = (JTable)e.getSource();
            //get the coordinates of the mouse click
            Point p = e.getPoint();
            // get the row index that contains that coordinate
            row= target.rowAtPoint(p);

            if (SwingUtilities.isRightMouseButton(e) && target == table && row >= 0) {
                target.removeRowSelectionInterval(0, row);
                maybeShowPopup(e);
            }
        }

        public void mouseReleased(MouseEvent e) {
            JTable target = (JTable)e.getSource();
            //get the coordinates of the mouse click
            Point p = e.getPoint();
            //get the row index that contains that coordinate
            row= target.rowAtPoint(p);

            if (SwingUtilities.isRightMouseButton(e) && target == table && row >= 0) {
                target.removeRowSelectionInterval(0, row);
                maybeShowPopup(e);
            }
        }

        private void maybeShowPopup(MouseEvent e) {
            if (e.isPopupTrigger()) {
                popup.show(e.getComponent(), e.getX(), e.getY());
            }
        }
    }//end inner class

    //empty methods for completeness of interface
    public void mousePressed(MouseEvent e) {
    }

    public void mouseReleased(MouseEvent e) {
    }

    public void mouseEntered(MouseEvent e) {
    }

    public void mouseExited(MouseEvent e) {
    }
    //end empty methods

    //return the main panel so that it can
    //be styled in the main JFrame
    Component getPanel() {
        return panel;
    }

    //return the main menubar so that it can
    //be styled in the main JFrame
    Component getMenuBar() {
        return this.menuBar;
    }

    //create nodes on the tree, using the root node as the start
    private void createNodes(DefaultMutableTreeNode top) {
        DefaultMutableTreeNode category = null;
        DefaultMutableTreeNode mailType = null;

        //make a child node of the root node
        category = new DefaultMutableTreeNode("Mailbox");
        top.add(category);

        //add children to the child node of the root node
        mailType = new DefaultMutableTreeNode(new MyTableModel("inbox", this.getTitles("inbox")));
        category.add(mailType);
        mailType = new DefaultMutableTreeNode(new MyTableModel("outbox", this.getTitles("outbox")));
        category.add(mailType);
        mailType = new DefaultMutableTreeNode(new MyTableModel("junk", this.getTitles("junk")));
        category.add(mailType);
        mailType = new DefaultMutableTreeNode(new MyTableModel("drafts", this.getTitles("drafts")));
        category.add(mailType);
        mailType = new DefaultMutableTreeNode(new MyTableModel("deleted", this.getTitles("deleted")));
        category.add(mailType);

        //make a child node of the root node
        category = new DefaultMutableTreeNode("My Custom Folders");
        top.add(category);

        //add children to the child node of the root node
        mailType = new DefaultMutableTreeNode(new MyTableModel("university", this.getTitles("university")));
        category.add(mailType);
        mailType = new DefaultMutableTreeNode(new MyTableModel("work", this.getTitles("work")));
        category.add(mailType);
    }

    //interacts with Database to get all e-mail metadata's from a folder
    public ArrayList<EmailMetadata> getTitles(String col){
        Connection conn = Database.getConnection();
        String query = "SELECT * FROM mailbox WHERE subtree='"+col+"'"
                + " ORDER BY datetime DESC";
        //temporary variables
        ArrayList<String> temp1 = new ArrayList<String>();
        ArrayList<String> temp2 = new ArrayList<String>();
        ArrayList<String> temp3 = new ArrayList<String>();
        ArrayList<String> temp4 = new ArrayList<String>();
        ArrayList<String> temp5 = new ArrayList<String>();
        ArrayList<String> temp6 = new ArrayList<String>();
        ArrayList<String> temp7 = new ArrayList<String>();
        //variable to be returned
        ArrayList<EmailMetadata> tableD = new ArrayList<EmailMetadata>();

        try {
            //execute query
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(query);
            while(rs.next())
            {
                //store the values of the respective columns
                //which is determined by column name
                temp1.add(rs.getString("datetime"));
                temp2.add(rs.getString("subtree"));
                temp3.add(rs.getString("sender"));
                temp4.add(rs.getString("receiver"));
                temp5.add(rs.getString("cc"));
                temp6.add(rs.getString("title"));
                temp7.add(rs.getString("body"));
            }
            rs.close();
            //Releases this Connection object's database and JDBC resources immediately
            Database.closeDatabase(conn);
        } catch (SQLException ex) {
            ex.printStackTrace();
        }

        //add the metadata objects to tableD
        for(int i=0;i<temp1.size();i++){
            tableD.add(new EmailMetadata(convertTime(temp1.get(i)),temp2.get(i),temp3.get(i),
                    temp4.get(i),temp5.get(i),temp6.get(i),temp7.get(i)));
        }

        return tableD;
    }

    //converts the epoch time to human readable time
    public String convertTime(String time) {
        Long l = Long.parseLong(time);
        return new java.text.SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new java.util.Date (l));

    }

    //interacts with Database to get the body of a particular e-mail
    private String getBody(String col, String timeReceived, String sender) {
        Connection conn = Database.getConnection();
        String query = "SELECT datetime, body FROM mailbox WHERE subtree='"+col+"'"
                + "AND sender='"+sender+"' ORDER BY datetime DESC";

        ArrayList<String> timeReceivedEpoch = new ArrayList<String>();
        //variable to be returned
        ArrayList<String> body = new ArrayList<String>();

        try {
            //execute query
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(query);
            while(rs.next())
            {
                //store the values of the respective columns
                //which is determined by column name
                //convert the datetime to human readable time
                timeReceivedEpoch.add(convertTime(rs.getString("datetime")));
                body.add(rs.getString("body"));
            }
            rs.close();
            //Releases this Connection object's database and JDBC resources immediately
            Database.closeDatabase(conn);
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        //check the database time values and find the correct index
        //of the given time; use that index to get the body
        return body.get(timeReceivedEpoch.indexOf(timeReceived));
    }

    //interacts with Database to return epoch time
    //using human-readable time as an input
    private String convertEpoch(String timeReceived) {
        Connection conn = Database.getConnection();
        String query = "SELECT datetime FROM mailbox";

        ArrayList<String> timeReceivedEpoch = new ArrayList<String>();
        //variable to be returned
        String epoch = "";

        try {
            //execute query
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(query);
            while(rs.next())
            {
                //store the values of the respective columns
                //which is determined by column name
                timeReceivedEpoch.add(rs.getString("datetime"));
            }
            rs.close();
            //Releases this Connection object's database and JDBC resources immediately
            Database.closeDatabase(conn);
        } catch (SQLException ex) {
            ex.printStackTrace();
        }

        //all that is needed is to match the given human readable time
        //with the correct epoch time and return that epoch time
        for(int i=0;i<timeReceivedEpoch.size();i++) {
            if(convertTime(timeReceivedEpoch.get(i)).equals(timeReceived)) {
                epoch = timeReceivedEpoch.get(i);
                break;
            }
        }

        return epoch;
    }

    //interacts with Database to change the subtree of a particular e-mail
    private void updateEmail(String subtree, String epoch, String sender) {
        Connection conn = Database.getConnection();
        //delete the corresponding row
        String query = "UPDATE mailbox SET subtree='"+subtree+"' WHERE datetime='"
                +epoch+"' AND sender='"+sender+"'";

        try {
            //execute query
            conn.setAutoCommit(false);
            Statement stmt = conn.createStatement();
            stmt.executeUpdate(query);
            conn.commit();
            //Releases this Connection object's database and JDBC resources immediately
            Database.closeDatabase(conn);
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }

    //interacts with Database to remove all the records
    //from database for e-mails in the deleted folder
    private void emptyDeleted() {
        Connection conn = Database.getConnection();
        //delete the corresponding row
        String query = "DELETE FROM mailbox WHERE subtree='deleted'";

        try {
            //execute query
            conn.setAutoCommit(false);
            Statement stmt = conn.createStatement();
            stmt.executeUpdate(query);
            conn.commit();
            //Releases this Connection object's database and JDBC resources immediately
            Database.closeDatabase(conn);
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }

    //create the GUI, layout the components, and show the whole frame
    private static void createAndShowGUI() {

        //the main JFrame with handles layout
        JFrame frame = new JFrame("Mail Browser");
        //create and set up the content pane
        EmailEngine newContentPane = new EmailEngine();

        //layout all the components on the main JFrame
        frame.add(newContentPane.getPanel(), BorderLayout.CENTER);
        frame.add(newContentPane.getMenuBar(), BorderLayout.NORTH);
        //configure the main JFrame
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.setSize(1250, 700);
     	//this centers the frame on the screen
        frame.setLocationRelativeTo(null);
    }

    public static void main(String[] args) {
        //schedule a job for the event-dispatching thread;
        //creating and showing this application's GUI
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}
